package com.lgx.group.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.lgx.common.exception.DataException;
import com.lgx.common.web.Constants;
import com.lgx.common.web.Pagination;
import com.lgx.mobile.entity.Topic;
import com.lgx.mobile.entity.TopicChatRecord;
import com.lgx.mobile.service.ITopicChatRecordService;
import com.lgx.mobile.service.ITopicService;
import com.lgx.mobile.vo.TopicVO;
import com.lgx.right.entity.User;
import com.lgx.right.entity.UserExpand;
import com.lgx.right.service.IUserExpandService;
import com.lgx.right.vo.UserVO;

@Controller
@RequestMapping("/topicChat")  
public class TopicChatController {
	@Autowired
	ITopicService topicService;
	
	public ITopicService getTopicService() {
		return topicService;
	}
	
	@Autowired
	ITopicChatRecordService topicChatRecordService;

	public ITopicChatRecordService getTopicChatRecordService() {
		return topicChatRecordService;
	}

	@Autowired
	IUserExpandService userExpandService;

	public IUserExpandService getUserExpandService() {
		return userExpandService;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/topicChat.ftl")
	public String list(HttpServletRequest request,HttpServletResponse response){
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://"
				+ request.getServerName() + ":" + request.getServerPort()
				+ path + "/";
		
		request.setAttribute("basePath", basePath);
		
		String pageNum = request.getParameter("page");
		String pageSize= request.getParameter("rows");
		
		if(StringUtils.isEmpty(pageSize))pageSize = Constants.PAGE_SIZE;
		if(StringUtils.isEmpty(pageNum))pageNum = Constants.FIRST_PAGE_NUM;
		
		Object[] params = new Object[10];
		
		String topicId = request.getParameter("topicId");
		
		//获得圈子及创建者信息
		TopicVO topicVO = this.topicService.findTopicVOByTopicId(Long.parseLong(topicId));
		request.setAttribute("topicVO", topicVO);
		
		//获得圈子内所有聊天记录
		Pagination topicChatRecordPage = this.topicChatRecordService.findTopicChatRecordPaginationByTopicId(Long.parseLong(topicId), params, 5, Integer.parseInt(pageNum));
		request.setAttribute("TopicChatRecordPage", topicChatRecordPage);
		
		request.setAttribute("pageNum", pageNum);
		
		//获取圈子内在线成员列表
		List<UserVO> onlineUserVOListInTopic = new ArrayList<UserVO>();
		Set<User> onlineUsers = (HashSet<User>) request.getSession().getAttribute(Constants.ONLINE_USER);//获得所有在线用户
		if(onlineUsers != null && onlineUsers.size() > 0){
			Object[] objOnlineUsers = onlineUsers.toArray();
			User onlineUser = new User();
			Topic topic = this.topicService.findTopicById(Long.parseLong(topicId));
			Set<User> users = topic.getUsers();
			Object[] objUsers = users.toArray();
			UserExpand userExpand = new UserExpand();
			UserVO userVO = new UserVO();
			for(int i=0;i<objOnlineUsers.length;i++){
				onlineUser = (User)objOnlineUsers[i];
				for(int j=0;j<objUsers.length;j++){
					userExpand = this.userExpandService.findUserExpandByUserId(((User)objUsers[i]).getId());
					if(onlineUser.getId() == userExpand.getUser().getId()){
						userVO.setUserId(onlineUser.getId()+"");
						userVO.setUsername(onlineUser.getUsername());
						userVO.setNickname(onlineUser.getNickname());
						userVO.setTruename(onlineUser.getTruename());
						userVO.setEmail(onlineUser.getEmail());
						userVO.setSex(onlineUser.getSex());
						userVO.setMobile(onlineUser.getMobile());
						userVO.setCardId(onlineUser.getCard().getId());
						userVO.setDegree(userExpand.getDegree());
						userVO.setLevel(userExpand.getLevel());
						userVO.setHeadImage(userExpand.getHeadImage());
						userVO.setFunType(userExpand.getFunType());
						userVO.setGiftRecord(userExpand.getGiftRecord());
						userVO.setPoints(userExpand.getPoints());
						userVO.setPointRecordDate(userExpand.getPointRecordDate());
						onlineUserVOListInTopic.add(userVO);
					}
				}
			}
		}
		request.setAttribute("onlineUserVOListInTopic", onlineUserVOListInTopic);
		
		return "topic/topicChat";
	}
	
	@RequestMapping("/index.htm")
	public String index(HttpServletRequest request,HttpServletResponse response){
		return "topic/topicChat";
	}
	
	@RequestMapping("/topicChatRecordSearch.htm")  
	public String userSearch(HttpServletRequest request,HttpServletResponse response) {
		String pageNum = request.getParameter("page");
		request.setAttribute("pageNum", pageNum);
		return "topic/topicChat";
	}
	
	@RequestMapping("/publish.htm")
	public String Publish(HttpServletRequest request,HttpServletResponse response) {
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://"
				+ request.getServerName() + ":" + request.getServerPort()
				+ path + "/";
		request.setAttribute("basePath", basePath);
		
		User onlineUser = (User) request.getSession().getAttribute(Constants.LOGIN_USER);//得到当前登录人信息
		//发表聊天内容
		String topicId = request.getParameter("topicId");
		String content = request.getParameter("content");
		
		TopicChatRecord topicChatRecord = new TopicChatRecord();
		topicChatRecord.setTopicId(Long.parseLong(topicId));
		topicChatRecord.setUserId(onlineUser.getId());
		topicChatRecord.setRecordDate(new Date());
		topicChatRecord.setContent(content);
		try {
			this.topicChatRecordService.createTopicChatRecord(topicChatRecord);
		} catch (DataException e) {
			e.printStackTrace();
			request.setAttribute("message", "发表失败！");
		}
		request.setAttribute("message", "发表成功！");
		
		try {
			response.sendRedirect(basePath + "topicChat/index.htm?topicId=" + topicId);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return "topic/topicChat";
	}
}
